<?php
/**
 * Created by PhpStorm.
 * User: fengyan
 * Date: 2017/4/7
 * Time: 下午10:56
 */

namespace app\admin\controller;
use app\admin\model;
use think\Controller;

class Base extends Controller
{
    /**
     * @var string
     */
    protected $templatePrefix = '';

    protected $model;

    /**
     * 初始化方法
     */
    protected function _initialize()
    {

    }

    /**
     * 读取站点所有配置 并动态添加到项目配置
     */
    protected function readconfig()
    {
        $configList = (new model\Config())->getConfigList();

        config($configList);

        return $this;
    }

    /**
     * 重写fetch方法
     * @param string $template
     * @param array $vars
     * @param array $replace
     * @param array $config
     * @return mixed
     */
    protected function fetch($template = '', $vars = [], $replace = [], $config = [])
    {
        if (config('is_open_custom_template_prefix')) {
            $template = $this->templatePrefix.''.$template;
        }
        return parent::fetch($template, $vars, $replace, $config); // TODO: Change the autogenerated stub
    }

    /**
     * 设置数据状态
     */
    public function setStatus()
    {
        if (!$this->request->isPost()) {
            $this->error('错误的请求');
        }
        $ids = input('param.ids', []);

        $status = input('param.status', null);

        if (empty($ids)) {
            $this->error('操作数据不能为空');
        }

        if ($status === null) {
            $this->error('数据状态不能为空');
        }

        if (is_array($ids)) {
            $ids = arr2str($ids);
        }

//        $re = $this->model->update(['status'=>$status], ['id'=>['in', $ids]], ['status']);

        $re = $this->model->where(['id'=>['in', $ids]])->setField('status', $status);
        if ($re === false) {
            $this->error('更新数据状态失败');
        }

        if (method_exists($this, 'afterSetStatus')) {
            $this->afterSetStatus();
        }
        $this->success('更新数据状态成功', cookie('__forward__'));
    }


    /**
     * 删除数据
     */
    public function delete()
    {
        $ids = input('param.ids', []);

        $status = -1;

        if (empty($ids)) {
            $this->error('操作数据不能为空');
        }

        if (is_array($ids)) {
            $ids = arr2str($ids);
        }

//        $re = $this->model->update(['status'=>$status], ['id'=>['in', $ids]], ['status']);
        $re = $this->model->where(['id'=>['in', $ids]])->setField('status', $status);

        if ($re === false) {
            $this->error('删除数据状态失败');
        }

        if (method_exists($this, 'afterDelete')) {
            $this->afterDelete();
        }

        $this->success('删除数据状态成功', cookie('__forward__'));
    }
}